//
//  HHTextField.m
//  Flower
//
//  Created by 花花 on 2016/12/7.
//  Copyright © 2016年 花花. All rights reserved.
//

#import "HHTextField.h"
#import "UITextField+HHExtension.h"
@interface HHTextField()
//左下角按钮
@property(nonatomic, strong) UIButton *lowerleftButton;
//左下角title
@property(nonatomic, copy) NSString *lowerleftTitle;

@property (nonatomic, assign)   BOOL willShowKeyboard;

@property (nonatomic, assign)   BOOL displayKeyboard;
@end
@implementation HHTextField
/*
 三种初始化方式:
 1.系统自带初始化
 2.自定义初始化
 3.xib
 不管是哪种方式都会调用setup方法
 */
-(instancetype)initWithFrame:(CGRect)frame{
    if (self = [super initWithFrame:frame]) {
        
        [self setup];
    }
    return self;

}
-(instancetype)initWithFrame:(CGRect)frame lowerlefttitle:(NSString *)lowerlefttitle{
    if (self = [super initWithFrame:frame]) {
        self.lowerleftTitle =[lowerlefttitle copy];
        [self setup];
    }
    return self;


}
-(void)awakeFromNib{
    
    [super awakeFromNib];
    [self setup];
    

}
-(void)setup{
    self.keyboardType =  UIKeyboardTypeNumberPad;
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardWillBeginShow:) name:UITextFieldTextDidBeginEditingNotification object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardWillEndShow:) name:UITextFieldTextDidEndEditingNotification object:nil];
    

}
-(void)dealloc{

    [[NSNotificationCenter defaultCenter]removeObserver:self];
}
-(void)keyboardWillShow:(NSNotification *)noti{
    if (self.keyboardType != UIKeyboardTypeNumberPad) return;
    
    if (!self.willShowKeyboard) {
        self.displayKeyboard = YES;
    return;
     }
    
    [self.lowerleftButton removeFromSuperview];
    self.lowerleftButton = nil;
    
    NSDictionary *userInfo = [noti userInfo];
    // 动画时间
    CGFloat animationDuration = [[userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];
    // 键盘的Frame
    CGRect kbEndFrame = [noti.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    CGFloat kbHeight = kbEndFrame.size.height;
    

    
    // 获取到最上层的window,这句代码很关键
    UIWindow *tempWindow = [[[UIApplication sharedApplication] windows] objectAtIndex:1];
    
    if ([[[UIDevice currentDevice] systemVersion] floatValue] > 9.0) {
        tempWindow = [[[UIApplication sharedApplication] windows] lastObject];
    }
    
    // 通过图层查看系统的键盘有UIKeyboardAutomatic这个View，第三方的对应位置的view为_UISizeTrackingView
    // 只有iOS 8.0以上需要
    if ([[[UIDevice currentDevice] systemVersion] floatValue] > 8.0) {
        if (![UIView hh_foundViewInView:tempWindow clazzName:@"UIKeyboardAutomatic"]) return;
    }
    
    // 这里因为用了第三方的键盘顶部，所有加了44
    if (self.adjustTextFeildH) {
        kbHeight = kbEndFrame.size.height - 44;
    }
    // 动画的轨迹
    NSInteger animationCurve = [[userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey] integerValue];
    
    CGFloat lowerleftbtnX = 0;
    CGFloat lowerleftbtnY = 0;
    CGFloat lowerleftbtnW = 0;
    CGFloat lowerleftbtnH = 0;
    
    if (screen_width ==320) {
        lowerleftbtnW = (screen_width-6)/3;
        lowerleftbtnH = (kbHeight -2)/4;
    }else if (screen_width ==375){
        lowerleftbtnW = (screen_width-8)/3;
        lowerleftbtnH = (kbHeight -2)/4;
    
    }else if (screen_width ==414){
        lowerleftbtnW = (screen_width-7)/3;
        lowerleftbtnH = kbHeight/4;
    }
    
    if (self.displayKeyboard) {
        lowerleftbtnY = screen_height - lowerleftbtnH;
    }else{
        lowerleftbtnY = screen_height +kbHeight -lowerleftbtnH;
    }
    
    UIButton *lowerleftbtn =[[UIButton alloc]initWithFrame:CGRectMake(lowerleftbtnX, lowerleftbtnY, lowerleftbtnW, lowerleftbtnH)];
    lowerleftbtn.backgroundColor =[UIColor redColor];
    lowerleftbtn.titleLabel.font = [UIFont systemFontOfSize:27];
    [lowerleftbtn setTitle:self.lowerleftTitle forState:(UIControlStateNormal)];
    [lowerleftbtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [lowerleftbtn setBackgroundImage:[self createImageWithColor:[UIColor whiteColor]] forState:UIControlStateHighlighted];
    [lowerleftbtn addTarget:self action:@selector(lowerleftButton:) forControlEvents:UIControlEventTouchUpInside];
    self.lowerleftButton = lowerleftbtn;
    // 添加按钮
    [tempWindow addSubview:lowerleftbtn];
    
    if (!self.displayKeyboard) {
        // 添加动画
        [UIView beginAnimations:nil context:NULL];
        [UIView setAnimationBeginsFromCurrentState:YES];
        [UIView setAnimationDuration:animationDuration];
        [UIView setAnimationCurve:animationCurve];
        lowerleftbtn.transform = CGAffineTransformTranslate(lowerleftbtn.transform, 0, -kbHeight);
        [UIView commitAnimations];
    }
    self.displayKeyboard = YES;
    
    
}
-(void)lowerleftButton:(UIButton *)btn{

    // 获得光标所在的位置
    NSUInteger insertIndex = [self selectedRange].location;
    
    NSMutableString *string = [NSMutableString stringWithString:self.text];
    
    [string replaceCharactersInRange:self.selectedRange withString:btn.currentTitle];
    
    // 重新赋值
    self.text = string;
    
    // 让光标回到插入文字后面
    [self setSelectedRange:NSMakeRange(insertIndex + 1, 0)];
    
    // 发出通知
    [[NSNotificationCenter defaultCenter] postNotificationName:UITextFieldTextDidChangeNotification object:self];
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        [[UIDevice currentDevice] playInputClick];
    });
}
-(void)keyboardWillHide:(NSNotification *)noti{
    if (self.keyboardType != UIKeyboardTypeNumberPad) return;
    self.displayKeyboard = NO;
    
}
-(void)keyboardWillBeginShow:(NSNotification *)noti{
    if (self.keyboardType != UIKeyboardTypeNumberPad) return;
    
    self.willShowKeyboard = noti.object == self;
    
}
-(void)keyboardWillEndShow:(NSNotification *)noti{
    
 if (self.keyboardType != UIKeyboardTypeNumberPad) return;
    self.willShowKeyboard = NO;
    NSDictionary *userInfo =[noti userInfo];
    CGFloat animationDuration = [[userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];
    NSInteger animationCurve = [[userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey] integerValue];
    // 添加动画
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationBeginsFromCurrentState:YES];
    [UIView setAnimationDuration:animationDuration];
    [UIView setAnimationCurve:animationCurve];
    self.lowerleftButton.transform = CGAffineTransformIdentity;
    [self.lowerleftButton removeFromSuperview];
    [UIView commitAnimations];
    
}
-(NSString *)lowerleftTitle{
    
    if (!_lowerleftTitle) {
        _lowerleftTitle = [NSString copy];
    }
    
    return _lowerleftTitle;
    
}
/**
 *  用颜色返回一张图片
 */
- (UIImage *)createImageWithColor:(UIColor *)color {
    CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return theImage;
}


@end
